
<template>
  <div>
    <!-- 标题和简介 -->
    <div class="edit-item">
      <el-row class="edit-item-row">
        <el-col :span="22">
          <div class="edit-item-title">{{title}}</div>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="titleEditOpen()" icon="el-icon-edit" circle></el-button>
        </el-col>
      </el-row>
      <div class="introduction">简介：{{introduction}}</div>
    </div>
    <!-- 问题和选项 -->
    <draggable :list="questions" handle=".handle" forceFallback:true :fallback-tolerance="1">
      <div class="edit-item" v-for="(question, index) in questions" v-bind:key="index">
        <el-row class="edit-item-row">
          <el-col :span="1" class="question-title">{{index + 1}}.</el-col>
          <el-col :span="17" class="question-title">{{question.title}}</el-col>
          <el-col :span="6">
            <el-button type="success" class="handle" icon="el-icon-s-operation" circle></el-button>
            <el-button type="primary" @click="startQuestionEdit(index)" icon="el-icon-edit" circle></el-button>
            <el-button type="danger" icon="el-icon-delete" circle @click="questionDelete(index)"></el-button>
          </el-col>
        </el-row>
        <el-radio-group v-if="question.topic == 1" class="radio-class">
          <div v-for="(select,index) in question.selects" v-bind:key="index">
            <el-radio :label="1" class="radio-item-class">{{select}}</el-radio>
            <br />
          </div>
        </el-radio-group>
        <div v-if="question.topic == 2" class="radio-class">
          <div v-for="(select,index) in question.selects" v-bind:key="index">
            <el-checkbox class="radio-item-class">{{select}}</el-checkbox>
            <br />
          </div>
        </div>
        <div v-if="question.topic==3" class="text-class">
          <el-input></el-input>
        </div>
      </div>
    </draggable>
    <div class="edit-item">
      <div class="edit-item-time-title">问卷填写截止时间</div>
      <div class="edit-item-time-box">
        <el-date-picker
          v-model="endtime"
          type="datetime"
          placeholder="选择日期时间"
          align="right"
          :picker-options="pickerOptions"
        ></el-date-picker>
      </div>
      <div class="edit-item-time-btns">
        <el-button type="primary" @click="saveAndRelease()">保存并发布</el-button>
        <el-button @click="save()">仅保存</el-button>
      </div>
    </div>
    <!-- 标题与简介编辑窗口 -->
    <el-dialog title="编辑" :visible.sync="titleEdit" width="500px">
      <el-form label-width="80px">
        <el-form-item label="标题">
          <el-input v-model="title_"></el-input>
        </el-form-item>
        <el-form-item label="简介">
          <el-input v-model="introduction_"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="titleEdit = false">取 消</el-button>
        <el-button type="primary" @click="editTitle()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 问题与选项编辑窗口 -->
    <el-dialog title="编辑问题" :visible.sync="questionEditFlag" width="500px">
      <!-- 更改问题类型 -->
      <div class="topic-select">
        <el-select v-model="tvalue" placeholder="请选择" size="mini" @change="change_topic()">
          <el-option v-for="item in topics"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            :disabled="item.disabled">
          </el-option>
        </el-select>
      </div>
      <!-- 编辑问题标题 -->
      <el-form label-width="80px">
        <el-form-item label="标题">
          <el-input v-model="tmpQuestion.title"></el-input>
        </el-form-item>
        <draggable v-if="tmpQuestion.topic!=3" :list="tmpQuestion.selects" handle=".handle">
          <el-row v-for="(select,index) in tmpQuestion.selects" v-bind:key="index">
            <el-col :span="16">
              <el-form-item :label="'选项'+(index+1)">
                <el-input v-model="tmpQuestion.selects[index]"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-button type="success" icon="el-icon-s-operation" class="handle" circle></el-button>
              <el-button type="danger" icon="el-icon-delete" circle @click="selectDelete(index)"></el-button>
            </el-col>
          </el-row>
        </draggable>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="tmpQuestion.topic!=3" type="warning" @click="selectAdd()">增加新选项</el-button>
        <el-button @click="questionEditFlag = false">取 消</el-button>
        <el-button type="primary" @click="questionEdit()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加问题 -->
    <div class="add-question-button">
      <div>
        <el-collapse-transition>
          <div v-show="showAddSele">
            <div class="transition-box">
              <el-button type="primary" circle @click="questionAdd(1)">单</el-button>
            </div>
            <div class="transition-box">
              <el-button type="primary" circle @click="questionAdd(2)">多</el-button>
            </div>
            <div class="transition-box">
              <el-button type="primary" circle @click="questionAdd(3)">填</el-button>
            </div>
          </div>
        </el-collapse-transition>
      </div>
      <el-button
        class="btns"
        type="primary"
        circle
        style="padding:25px"
        @click="questionSort()"
        title="问题排序"
      >排</el-button>
      <el-button
        class="btns"
        type="primary"
        icon="el-icon-plus"
        circle
        style="padding:25px"
        @click="showAddSele=!showAddSele"
        title="添加问题"
      ></el-button>
    </div>
  </div>
</template>

<script>
import draggable from 'vuedraggable'
export default {
  data() {
    return {
      radio: 1,
      title: '问卷标题',
      title_: '',
      // 用于编辑问卷时选择问卷类型
      topics: [
        { value: 1, label: '单选' },
        { value: 2, label: '多选' },
        { value: 3, label: '填空' }
      ],
      tvalue: '',
      // 简介
      introduction: '',
      introduction_: '',
      questionDeleteFlag: false,
      titleEdit: false,
      questionEditFlag: false,
      tmpQuestion: {},
      index_: 0,
      questionnaireid: '',
      showAddSele: false, // 显示添加问题类型
      questions: [
        {
          title: '单选',
          topic: 1,
          selects: ['单选1', '单选2', '单选3']
        },
        {
          title: '多选',
          topic: 2,
          selects: ['多选1', '多选2', '多选3']
        },
        {
          title: '填空题',
          topic: 3,
          selects: []
        }
      ],
      pickerOptions: {
        shortcuts: [
          {
            text: '未来1天',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() + 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: '未来7天',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          },
          {
            text: '未来30天',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 30)
              picker.$emit('pick', date)
            }
          }
        ]
      },
      endtime: ''
    }
  },
  created: async function() {
    var res = this.$route.query.res
    // console.log(res)
    if (res === '') {
      return
    }
    this.questionnaireid = res.data.questionnaireid
    this.title = res.data.title
    this.questions = res.data.questions
    this.introduction = res.data.introduction
    const date = new Date()
    this.endtime = date.setTime(res.data.endtime * 1000)
  },
  components: {
    draggable
  },
  methods: {
    editTitle: function() {
      this.titleEdit = false
      this.title = this.title_
      this.introduction = this.introduction_
    },
    titleEditOpen: function() {
      this.titleEdit = true
      this.title_ = this.title
      this.introduction_ = this.introduction
    },
    startQuestionEdit: function(index) {
      this.index_ = index
      this.questionEditFlag = true
      this.tmpQuestion = JSON.parse(JSON.stringify(this.questions[index]))
      this.tvalue = this.tmpQuestion.topic
    },
    questionEdit: function() {
      this.questionEditFlag = false
      this.questions[this.index_] = this.tmpQuestion
      this.$message({
        message: '问题修改成功',
        type: 'success'
      })
      // console.log(this.questions[this.index_])
      // console.log(this.tmpQuestion)
    },
    questionDelete: function(index) {
      this.$confirm('你确认要删除吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.questions.splice(index, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    selectDelete: function(index) {
      this.$confirm('你确认要删除吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.tmpQuestion.selects.splice(index, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    selectAdd: function() {
      this.tmpQuestion.selects.push('新选项')
    },
    created: function() {
      this.questionnaireid = this.$route.query.questionnaireid
    },
    async saveAndRelease() {
      if (this.questions.length < 1) {
        this.$message.error('问卷最少需要一个问题')
        return
      }
      if (this.endtime === '') {
        this.$message.error('发布问卷需填写截止时间')
        return
      }
      if (this.endtime !== '') {
        // console.log(Date.now())
        if (this.endtime < Date.now()) {
          this.$message.error('发布开始时间不能早于当前时间')
          return
        }
      }
      // 调用保存问卷接口前，先给新问卷获取一个问卷id（若无），即调用新建问卷接口
      if (this.questionnaireid === '') {
        const { data: res } = await this.$http.get('add')
        // console.log(res.data.questionnaireid)
        if (res.meta.status !== 200) {
          this.$message.error('保存失败，请重试')
          return
        }
        this.questionnaireid = res.data.questionnaireid
      }
      // 调用保存接口
      var data = {}
      data.questionnaireid = this.questionnaireid
      data.title = this.title
      data.introduction = this.introduction
      data.questions = this.questions
      data.endtime = this.endtime.getTime() / 1000
      const { data: res } = await this.$http.post('save', data)
      if (res.meta.status !== 200) {
        this.$message.error('保存失败，请重试')
        return
      }
      // 发布问卷接口如下
      data = {}
      data.questionnaireid = this.questionnaireid
      const { data: res2 } = await this.$http.put('release', data)
      if (res2.meta.status !== 200) {
        // 跳转到发布失败页面
        this.$message.error('发布失败，请重试')
        this.$router.push('/releasefail')
      }
      this.$message.success('发布成功')
      // 跳转到发布成功页面
      this.$router.push({
        path: '/releasesuccess',
        query: {
          link: res2.data.link,
          questionnaireid: this.questionnaireid
        }
      })
    },
    async save() {
      // 调用保存问卷接口前，先给新问卷获取一个问卷id（若无），即调用新建问卷接口
      if (this.questionnaireid === '') {
        const { data: res } = await this.$http.get('add')
        // console.log(res.data.questionnaireid)
        if (res.meta.status !== 200) {
          this.$message.error('保存失败，请重试')
          return
        }
        this.questionnaireid = res.data.questionnaireid
      }
      // 调用保存接口
      var data = {}
      data.questionnaireid = this.questionnaireid
      data.title = this.title
      data.introduction = this.introduction
      data.questions = this.questions
      // data.endtime = this.endtime.getTime() / 1000

      var { data: res } = await this.$http.post('save', data)
      if (res.meta.status !== 200) {
        this.$message.error('保存失败，请重试')
        return
      }
      this.$message.success('保存成功')
      // 保存成功后跳转回 /questionnaire
      this.$router.push('/questionnaire')
    },
    // 在questions后追加新问题
    questionAdd: function(newTopic) {
      if (newTopic === 1) {
        this.questions.push({
          title: '单选',
          topic: 1,
          selects: ['单选1', '单选2', '单选3']
        })
      } else if (newTopic === 2) {
        this.questions.push({
          title: '多选',
          topic: 2,
          selects: ['多选1', '多选2', '多选3']
        })
      } else if (newTopic === 3) {
        this.questions.push({
          title: '填空题',
          topic: 3,
          selects: []
        })
      }
      this.$message({
        message: '添加问题成功',
        type: 'success'
      })
    },
    questionSort() {
      // this.questions.sort((a, b) => a.topic - b.topic)
      this.$confirm('此操作将对问题进行排序, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
        // this.questions.sort((a, b) => a.topic - b.topic)
      })
        .then(() => {
          this.questions.sort((a, b) => a.topic - b.topic)
          this.$message({
            type: 'success',
            message: '排序成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消排序'
          })
        })
    },
    // 修改问卷类型
    change_topic: function() {
      var temp = ''
      if (this.tmpQuestion.title !== '单选' && this.tmpQuestion.title !== '填空' && this.tmpQuestion.title !== '多选') {
        temp = this.questions[this.index_].title
        console.log(temp)
      }
      if (this.tvalue === 1) {
        this.tmpQuestion = {
          title: (temp !== '') ? temp : '单选',
          topic: 1,
          selects: ['单选1', '单选2', '单选3']
        }
      } else if (this.tvalue === 2) {
        this.tmpQuestion = {
          title: (temp !== '') ? temp : '多选',
          topic: 2,
          selects: ['多选1', '多选2', '多选3']
        }
      } else if (this.tvalue === 3) {
        this.tmpQuestion = {
          title: (temp !== '') ? temp : '填空',
          topic: 3,
          selects: []
        }
      }
      this.$message({
        message: '问题类型更改成功',
        type: 'success'
      })
    }
  }
}
</script>

<style>
.edit-item {
  background-color: white;
  margin: 0 auto;
  margin-bottom: 30px;
  max-width: 700px;
}
.title-item {
  padding: 10px;
  text-align: center;
}
.input-click-item {
  height: 100px;
}
.edit-item-title {
  text-align: center;
  font-size: 28px;
}
.edit-item-row {
  padding: 20px;
  padding-right: 0;
  padding-bottom: 0;
}
.introduction {
  padding: 30px;
}
.input-item {
  padding: 10px;
}
.radio-class {
  padding: 20px;
  padding-top: 10px;
}
.radio-item-class {
  padding: 9px;
}
.question-title {
  padding: 5px;
  margin: 0;
}
.text-class {
  padding-left: 40px;
  padding-right: 40px;
  padding-top: 15px;
  padding-bottom: 20px;
}
.edit-item-time-title {
  text-align: center;
  padding-top: 15px;
  padding-bottom: 5px;
}
.edit-item-time-box {
  text-align: center;
  padding-top: 15px;
  padding-bottom: 5px;
}
.edit-item-time-btns {
  text-align: center;
  padding-top: 15px;
  padding-bottom: 15px;
}
.add-question-button {
  position: fixed;
  bottom: 30px;
  right: 50px;
}
.topic-select {
  margin-top: -20px;
  margin-left: 80px;
  padding-bottom: 20px;
}
.transition-box {
  text-align: right;
  color: #fff;
  padding: 10px 10px;
  box-sizing: border-box;
}
</style>
